﻿using JX.Application;
using JX.Core.Entity;
using JX.Infrastructure;
using JX.Infrastructure.Common;
using JX.Infrastructure.Field;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace JXWebSite.Components
{
	/// <summary>
	/// 模型字段查看视图组件
	/// </summary>
	[ViewComponent(Name = "FieldViewControl")]
	public class FieldViewControlViewComponent : ViewComponent
	{
		private readonly IUserGroupsServiceAppDapper _userGroupsServiceApp;
		private readonly IRolesServiceAppDapper _rolesServiceApp;
		private readonly IModelsServiceAppDapper _ModelsService;
		private readonly INodesServiceAppDapper _NodesService;
		private readonly ICommonInfoServiceAppDapper _CommonInfoService;
		private readonly IFlowProcessServiceAppDapper _FlowProcessService;
		private readonly IStatusServiceAppDapper _StatusService;
		/// <summary>
		/// 依赖注入
		/// </summary>
		/// <param name="userGroupsServiceApp"></param>
		/// <param name="rolesServiceApp"></param>
		/// <param name="NodesService"></param>
		/// <param name="ModelsService"></param>
		/// <param name="CommonInfoService"></param>
		/// <param name="StatusService"></param>
		/// <param name="FlowProcessService"></param>
		public FieldViewControlViewComponent(IUserGroupsServiceAppDapper userGroupsServiceApp,
			IRolesServiceAppDapper rolesServiceApp,
			INodesServiceAppDapper NodesService,
			IModelsServiceAppDapper ModelsService,
			ICommonInfoServiceAppDapper CommonInfoService,
			IStatusServiceAppDapper StatusService,
			IFlowProcessServiceAppDapper FlowProcessService)
		{
			_userGroupsServiceApp = userGroupsServiceApp;
			_rolesServiceApp = rolesServiceApp;
			_ModelsService = ModelsService;
			_NodesService = NodesService;
			_CommonInfoService = CommonInfoService;
			_FlowProcessService = FlowProcessService;
			_StatusService = StatusService;
		}
		/// <summary>
		/// 异步调用
		/// </summary>
		/// <param name="viewModel"></param>
		/// <returns></returns>
		public async Task<IViewComponentResult> InvokeAsync(FieldControlViewModel viewModel =null)
		{
			viewModel = await GetViewModelAsync(viewModel);
			return View(viewModel);
		}

		private async Task<FieldControlViewModel> GetViewModelAsync(FieldControlViewModel viewModel)
		{
			if (viewModel == null)
			{
				viewModel = new FieldControlViewModel();
			}
			if (viewModel.IsAdminManage)
			{
				viewModel.IsShow = await _rolesServiceApp.AccessCheckFieldPermission(OperateCode.ContentFieldInput, viewModel.ModelID, viewModel.FieldName);
			}
			else
			{
				viewModel.IsShow = await _userGroupsServiceApp.AccessCheckFieldPermission(OperateCode.ContentFieldInput, viewModel.ModelID, viewModel.FieldName);
			}
			if (viewModel.DataSource.Rows.Count > 0)
			{
				//准备字段控件的字段值
				switch (viewModel.FieldType)
				{
					case FieldType.RegionType:
						viewModel.FieldValue = InitRegionTypeValue(viewModel.DataSource.Rows[0][viewModel.FieldName + "_Country"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Province"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_City"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area"].ToString(), viewModel.Settings[2], DataConverter.CLng(viewModel.Settings[1], 5));
						viewModel.FieldValue = viewModel.FieldValue.Replace(",", string.Empty);
						break;
					case FieldType.RegionTypeFive:
						viewModel.FieldValue = InitRegionFiveTypeValue(viewModel.DataSource.Rows[0][viewModel.FieldName + "_Country"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Province"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_City"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area1"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area2"].ToString(), viewModel.Settings[2], DataConverter.CLng(viewModel.Settings[1], 5));
						viewModel.FieldValue = viewModel.FieldValue.Replace(",", string.Empty);
						break;
					case FieldType.RegionTypeText:
						viewModel.FieldValue = InitRegionTypeTextValue(viewModel.DataSource.Rows[0][viewModel.FieldName + "_Country"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Province"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_City"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Area"].ToString() + "," + viewModel.DataSource.Rows[0][viewModel.FieldName + "_Address"].ToString(), viewModel.Settings[2], DataConverter.CLng(viewModel.Settings[1], 5));
						viewModel.FieldValue = viewModel.FieldValue.Replace(",", string.Empty);
						break;
				}
				if (viewModel.FieldType != FieldType.ValidateCodeType
					&& viewModel.FieldType != FieldType.RegionType
					&& viewModel.FieldType != FieldType.RegionTypeFive
					&& viewModel.FieldType != FieldType.RegionTypeText
					&& viewModel.DataSource.Columns.Contains(viewModel.FieldName))
				{
					viewModel.FieldValue = DataConverter.ToString(viewModel.DataSource.Rows[0][viewModel.FieldName]);
				}
				//转换字段值为显示方式
				switch (viewModel.FieldType)
				{
					case FieldType.StatusType:
						viewModel.FieldValue = _StatusService.Get(p => p.StatusCode == viewModel.FieldValue.ToInt32(0)).StatusName;
						break;
					case FieldType.NodeType:
						viewModel.FieldValue = _NodesService.ShowNodeNavigation(viewModel.FieldValue.ToInt32());
						break;
					case FieldType.InfoType:
						string strInfoTypeHtml = string.Empty;
						if (viewModel.GID > 0)
						{
							foreach (var item in _CommonInfoService.GetInfoList(viewModel.GID))
							{
								strInfoTypeHtml = "<span>" + _NodesService.ShowNodesAndRootNavigation(item.NodeID.ToInt32()) + "<br /></span>";
							}
						}
						if (strInfoTypeHtml.Length <= 0)
						{
							strInfoTypeHtml = "<span>无其它栏目<br /></span>";
						}
						strInfoTypeHtml = "<div style=\"margin: 0; padding: 0; float: left;\">" + strInfoTypeHtml + "</div>";
						viewModel.FieldValue = strInfoTypeHtml;
						break;
					case FieldType.NodeCategory:
						string strNodeCategoryHtml = string.Empty;
						string[] arrNodeID = viewModel.FieldValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
						foreach (string strID in arrNodeID)
						{
							strNodeCategoryHtml += "<p>" + _NodesService.ShowNodesAndRootNavigation(DataConverter.CLng(strID)) + "</p>";
						}
						viewModel.FieldValue = strNodeCategoryHtml;
						break;
					case FieldType.IndustryCategory:
						string strIndustryCategoryHtml = string.Empty;
						foreach (string node in viewModel.FieldValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
						{
							if (DataConverter.CLng(node) > 0)
							{
								strIndustryCategoryHtml = strIndustryCategoryHtml + _NodesService.GetCacheNodeById(DataConverter.CLng(node)).NodeName + " ";
							}
						}
						viewModel.FieldValue = strIndustryCategoryHtml;
						break;
					case FieldType.MoneyType:
						viewModel.FieldValue = viewModel.FieldValue.ToDecimal().ToString("0.00");
						break;
					case FieldType.DateTimeType:
						viewModel.FieldValue = InitDateTimeTypeTextValue(viewModel.FieldValue, viewModel.Settings[1]);
						break;
					case FieldType.BoolType:
						viewModel.FieldValue = (DataConverter.CBoolean(viewModel.FieldValue)) ? "是" : "否";
						break;
					case FieldType.PictureType:
					case FieldType.MultiplePhotoType:
						viewModel.FieldValue = Utility.GetPicHtml(viewModel.FieldValue);
						break;
					case FieldType.ListBoxType:
						string strListBoxResult = viewModel.FieldValue;
						string strListBoxSource = viewModel.Settings[0];
						string[] arrListBoxSource = strListBoxSource.Split(new string[] { "$$$" }, StringSplitOptions.RemoveEmptyEntries);
						foreach (string strItem in arrListBoxSource)
						{
							string[] arrItem = strItem.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
							if (arrItem[1] == viewModel.FieldValue)
							{
								strListBoxResult = arrItem[0];
								break;
							}
						}
						viewModel.FieldValue = strListBoxResult;
						break;
					case FieldType.ListBoxDataType:
						string strSelectSQL = viewModel.Settings[0];
						string strSelectText = viewModel.Settings[1];
						string strSelectValue = viewModel.Settings[2];
						string strSelectDataType = viewModel.Settings[3];
						if (strSelectDataType == "Int")
						{
							string[] arrSQL = strSelectSQL.Split(new string[] { "where" }, StringSplitOptions.RemoveEmptyEntries);
							strSelectSQL = arrSQL[0] + " where " + strSelectValue + " in (" + viewModel.FieldValue + ")";
							var dtSelect = _ModelsService.GetDataTableBySql(strSelectSQL);
							string strItem = "";
							foreach (DataRow row in dtSelect.Rows)
							{
								strItem += row[strSelectText].ToString() + " ";
							}
							viewModel.FieldValue = strItem;
						}
						break;
					case FieldType.QRCodeType:
						if(!string.IsNullOrEmpty(viewModel.FieldValue))
						{
							viewModel.FieldValue = Utility.GetPicHtml(viewModel.FieldValue);
						}
						break;

				}
			}
			return viewModel;
		}

		/// <summary>
		/// 初始化区域类型控件的字段值
		/// </summary>
		/// <param name="fieldValue">字段值</param>
		/// <param name="defaultValue">默认值</param>
		/// <param name="mode">显示类型(1：国家+省；2：国家+省+市；3：国家+省+市+县；4：省+市；5：省+市+县；6：市+县；)</param>
		/// <returns></returns>
		private string InitRegionTypeValue(string fieldValue, string defaultValue, int mode)
		{
			string str = "";
			string[] strArray = fieldValue.Split(new char[] { ',' });
			string[] strArray2 = defaultValue.Split(new char[] { ',' });
			if ((mode == 6) || (mode == 5) || (mode == 4))
			{
				if (string.IsNullOrEmpty(strArray[0]))
				{
					strArray[0] = strArray2[0];
				}
				if ((mode == 6) && string.IsNullOrEmpty(strArray[1]))
				{
					strArray[1] = strArray2[1];
				}
			}
			for (int i = 0; i < 4; i++)
			{
				str = str + strArray[i] + ",";
			}
			return str.Remove(str.Length - 1);
		}
		/// <summary>
		/// 初始化区域(5级)类型控件的字段值
		/// </summary>
		/// <param name="fieldValue">字段值</param>
		/// <param name="defaultValue">默认值</param>
		/// <param name="mode">显示类型(1：国家+省+市+县+街道+小区；2：省+市+县+街道+小区；3：市+县+街道+小区；)</param>
		/// <returns></returns>
		private string InitRegionFiveTypeValue(string fieldValue, string defaultValue, int mode)
		{
			string str = "";
			string[] strArray = fieldValue.Split(new char[] { ',' });
			string[] strArray2 = defaultValue.Split(new char[] { ',' });
			if (string.IsNullOrEmpty(strArray[0]))
			{
				strArray[0] = strArray2[0];
			}
			if ((mode == 3) && string.IsNullOrEmpty(strArray[1]))
			{
				strArray[1] = strArray2[1];
			}
			for (int i = 0; i < 6; i++)
			{
				str = str + strArray[i] + ",";
			}
			return str.Remove(str.Length - 1);
		}
		/// <summary>
		/// 初始化区域类型控件的字段值
		/// </summary>
		/// <param name="fieldValue">字段值</param>
		/// <param name="defaultValue">默认值</param>
		/// <param name="mode">显示类型(1：国家+省；2：国家+省+市；3：国家+省+市+县；4：省+市；5：省+市+县；6：市+县；)</param>
		/// <returns></returns>
		private string InitRegionTypeTextValue(string fieldValue, string defaultValue, int mode)
		{
			string str = "";
			string[] strArray = fieldValue.Split(new char[] { ',' });
			string[] strArray2 = defaultValue.Split(new char[] { ',' });
			if ((mode == 6) || (mode == 5) || (mode == 4))
			{
				if (string.IsNullOrEmpty(strArray[0]))
				{
					strArray[0] = strArray2[0];
				}
				if ((mode == 6) && string.IsNullOrEmpty(strArray[1]))
				{
					strArray[1] = strArray2[1];
				}
			}
			for (int i = 0; i < 5; i++)
			{
				str = str + strArray[i] + ",";
			}
			return str.Remove(str.Length - 1);
		}
		/// <summary>
		/// 初始化日期字段的显示值
		/// </summary>
		/// <param name="fieldValue"></param>
		/// <param name="mode"></param>
		/// <returns></returns>
		private string InitDateTimeTypeTextValue(string fieldValue, string mode)
		{
			DateTime dateTime = fieldValue.ToDateTime(DateTime.MinValue);
			if(dateTime== DateTime.MinValue)
			{
				return string.Empty;
			}
			string format = string.Empty;
			switch (mode)
			{
				case "year":
					format = "yyyy";
					break;
				case "month":
					format = "yyyy-MM";
					break;
				case "date":
					format = "yyyy-MM-dd";
					break;
				case "time":
					format = "HH:mm:ss";
					break;
				case "datetime":
					format = "yyyy-MM-dd HH:mm:ss";
					break;
			}
			return dateTime.ToString(format);
		}
	}
}
